package com.luxiu.extensionlib.dialog

import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.view.WindowManager
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import androidx.viewbinding.ViewBinding
import com.luxiu.extensionlib.R
import kotlin.reflect.KClass

abstract class BaseDialog<T : ViewBinding>(private val bindingClass: KClass<T>, var gravity: Int = Gravity.CENTER) : DialogFragment() {
    open val dimAmount = 0.2f
    protected lateinit var mBinding: T

    open val height = -1
    open val cancelOutside = true
    open val mTag = "BaseBottomDialog"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(STYLE_NO_TITLE, R.style.ExtensionBottomDialog)
    }

    @Suppress("UNCHECKED_CAST")
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): View? {
        dialog!!.window!!.requestFeature(Window.FEATURE_NO_TITLE)
        dialog!!.setCanceledOnTouchOutside(cancelOutside)
        mBinding = bindingClass.java.getDeclaredMethod("inflate", LayoutInflater::class.java).invoke(null, layoutInflater) as T
        bindView()
        return mBinding.root
    }


    abstract fun bindView()

    override fun onStart() {
        super.onStart()
        val window = dialog!!.window
        val params = window!!.attributes
        params.dimAmount = dimAmount
        params.width = 900
        //        params.width =
        if (height > 0) {
            params.height = height
        } else {
            params.height = WindowManager.LayoutParams.WRAP_CONTENT
        }
        params.gravity = gravity
        window.attributes = params
    }

    fun show(fragmentManager: FragmentManager) {
        show(fragmentManager, mTag)
    }

}